<template>
  <a-drawer v-model:visible="vdata.visible" title="新增机构网点渠道" width="40%" :mask-closable="false" @close="closeHandler">
    <a-tabs v-model:activeKey="vdata.singleActiveKey" @change="changehdler">
      <a-tab-pane :key="1" tab="单个渠道码上传" />
      <a-tab-pane :key="2" tab="多个渠道码上传" />
    </a-tabs>

    <div v-if="vdata.singleActiveKey === 1" class="container">
      <a-form
        ref="formRef"
        layout="vertical"
        :model="vdata.saveObject"
        :label-col="{ span: 24 }"
        :wrapper-col="{ span: 24 }"
        class="form"
        :rules="rules"
      >
        <a-row>
          <a-col :span="12">
            <a-form-item label="公众号归属机构" name="agentNo" :wrapper-col="{ span: 16 }">
              <GzTreeSelect ref="gzThreeRef" v-model:value="vdata.saveObject['agentNo']" :showLevel="3" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="微信公众号" name="appId" :wrapper-col="{ span: 16 }">
              <a-select v-model:value="vdata.saveObject['appId']" :options="vdata.saveObject['agentNo'] ? officialList : []" placeholder="请选择微信公众号" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-col :span="12">
          <a-form-item
            label="网点编码"
            name="channelCode"
            :wrapper-col="{ span: 16 }"
          >
            <a-input
              v-model:value="vdata.saveObject['channelCode']"
              placeholder="请输入网点编码"
            />
          </a-form-item>
        </a-col>
      </a-form>
      <div class="drawer-btn-center">
        <a-button type="primary" @click="uploadChannelHandler(0)">
          <check-outlined />
          新增渠道
        </a-button>
      </div>
    </div>
    <div v-else class="container">
      <a-form
        ref="formRef"
        layout="vertical"
        :model="vdata.saveObject"
        :label-col="{ span: 24 }"
        :wrapper-col="{ span: 24 }"
        class="form"
        :rules="rules"
      >
        <a-row>
          <a-col :span="12">
            <a-form-item label="公众号归属机构" name="agentNo" :wrapper-col="{ span: 16 }">
              <GzTreeSelect ref="gzThreeRef" v-model:value="vdata.saveObject['agentNo']" :showLevel="3" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="微信公众号" name="appId" :wrapper-col="{ span: 16 }">
              <a-select v-model:value="vdata.saveObject['appId']" :options="vdata.saveObject['agentNo'] ? officialList : []" placeholder="请选择微信公众号" />
            </a-form-item>
          </a-col>
          <a-col v-show="vdata.saveObject['agentNo']" :span="24">
            <a-form-item name="fileList">
              <template #label>
                <span style="margin-right: 20px">文件上传</span>
                <a-button class="item" type="link" style="padding: 4px 0" @click="downloadTemplate">
                  机构网点渠道模板下载
                </a-button>
              </template>
              <a-upload-dragger
                v-model:fileList="vdata.saveObject['fileList']"
                :action="vdata['action']"
                :data="vdata.formParams"
                :maxCount="1"
                accept=".xlsx, .xls"
                name="file"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <p class="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p class="ant-upload-text">拖动到此处上传，或<a>点击上传</a></p>
                <p class="ant-upload-hint">
                  <b style="color: #ff4d4f">每次只能上传一个文件，</b>限制文件格式为XLS/XLSX。
                </p>
              </a-upload-dragger>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    
    <!-- 列表展示 -->
    <GzTable
      ref="infoTableRef"
      :table-columns="tableColumns"
      :pagination="true"
      :scrollX="600"
      :dataSource="resultList"
    >
      <template #topBtnSlot>
        <a-button type="primary" :disabled="resultList.length == 0 || exportList.length == 0" @click="exportCode">
          <export-outlined />导出渠道码
        </a-button>
      </template>
    </GzTable>
  </a-drawer>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, getCurrentInstance, defineExpose, watch, nextTick } from 'vue'
import * as XLSX from 'xlsx'
import { req, $getUploadFormParams, API_URL_ACTIVITY_CHANNEL_ADD, API_URL_ACTIVITY_CHANNEL_EXPORT,API_URL_ACTIVITY_CHANNEL_ADDONE } from '@/api/manage'
import { $getAgentWxList } from '@/api/activityManage/activityCreate/index'
import { exportChannelCode } from '@/views/channel/channelUtils'

const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
const props = defineProps(['callBackFunc'])

const infoTableRef = ref()
const formRef = ref()
const gzThreeRef = ref()
// 数据源
const vdata: any = reactive({
  singleActiveKey: 1, // 单OR多
  fileList: [], //上传文件列表
  saveObject: {},
  visible: false, //是否显示
  action: '', //上传地址
})

// 列表表头
const tableColumns = [
  { key: 'channelCode', title: '网点编码', dataIndex: 'channelCode' },
  { key: 'errorMessage', title: '导入结果', dataIndex: 'errorMessage' },
]

const rules: any = {
  fileList: [{ required: true, message: '请上传文件', trigger: 'change' }],
  agentNo: [{ required: true, message: '请选择公众号归属机构', trigger: 'change' }],
  channelCode: [{ required: true, message: '请填写网点编码', trigger: 'change' }],
  appId: [{ required: true, message: '请选择微信公众号', trigger: 'change' }],
}
// 查询机构小程序/公众号列表接口  0微信公众号   1微信小程序 
const officialList = ref([])
async function getAgentWxList(agentNo){
  const res = await $getAgentWxList({ agentNo, type: 0 })
  officialList.value = res.map(item => ({ label: item.name, value: item.appId }))
}
// 监听机构变化 重新请求小程序/公众号列表
watch(() => vdata.saveObject.agentNo, async (newVal) => {
  if (newVal) {
    getAgentWxList(newVal)
  }
})

/**
 * 文件上传
 */
function beforeUpload(file) {
  // 校验文件大小 不大于20MB
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    $infoBox.message.warn('文件大小不能超过20MB！')
    return false
  }
  // 校验文件格式
  const isExcel = /\.(xlsx|xls)$/.test(file.name)
  if (!isExcel) {
    $infoBox.message.warn('文件格式必须为XLS/XLSX！')
    return false
  }
  return $getUploadFormParams(file, 'upload').then((res) => {
    vdata.action = res.formActionUrl // action
    vdata.formParams = res.formParams //表单组件
    vdata.saveObject.ossFileUrl = res.ossFileUrl
  })
}
function uploadChange(info) {
  if (info.file.status === 'error') {
    // 上传异常
    vdata.saveObject.fileList = []
    $infoBox.message.error('上传异常,请联系系统管理员')
  }

  if (info.file.status === 'done') {
    // 上传成功
    uploadChannelHandler(1)
  }
}
const exportList = ref([])
const resultList = ref([])
/**
 * 渠道上传
 * @param type 0 单个渠道 1 批量上传
*/
async function uploadChannelHandler(type = 0) {
  await formRef.value.validate()  // 表单校验
  // 数据拷贝
  const payload = {...vdata.saveObject}
  let reqUrl:String = ''
  if(type === 0){ // 单文件上传
    reqUrl = API_URL_ACTIVITY_CHANNEL_ADDONE
  }else{
    reqUrl = API_URL_ACTIVITY_CHANNEL_ADD
  }
  req.add(reqUrl, payload).then((res, error) => {
    exportList.value = res.export
    resultList.value = res.result
    if (error && error.length > 0) {
      let channelError1: any = []
      let channelError2: any = []
      let channelError3: any = []
      let channelError4: any = []
      error.forEach((item) => {
        if (item.errType === 1) {
          channelError1.push(item.channelName)
        } else if (item.errType === 2) {
          channelError2.push(item.channelName)
        } else if (item.errType === 3) {
          channelError3.push(item.channelName)
        } else if (item.errType === 4) {
          channelError4.push(item.channelName)
        }
      })
      // 去重 set
      channelError1 = Array.from(new Set(channelError1))
      channelError2 = Array.from(new Set(channelError2))
      channelError3 = Array.from(new Set(channelError3))
      channelError4 = Array.from(new Set(channelError4))

      // channelError2 = Array.from(new Set(channelError2))
      let message = ''
      message +=
        channelError1.length > 0
          ? `已存在渠道名单中【${channelError1.join(',')}】`
          : ''
      message +=
        channelError2.length > 0
          ? `商户不存在【${channelError2.join(',')}】`
          : ''
      message +=
        channelError3.length > 0
          ? `未设置区域限制【${channelError3.join(',')}】`
          : ''
      message +=
        channelError4.length > 0
          ? `商户不属于该机构【${channelError4.join(',')}】`
          : ''
      $infoBox.message.error(message)
      return
    }
    // 刷新渠道列表
    if(res.result[0].errType !== undefined){
      $infoBox.message.warn(res.result[0].errorMessage)
    }else{
      $infoBox.message.success(res.result[0].errorMessage)
    }
    props.callBackFunc()
  })
}

// excel表格导出函数数据
const exportToExcel = (item, name) => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()

  // 创建一个工作表
  const worksheet = XLSX.utils.aoa_to_sheet([...item])

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成Excel文件
  XLSX.writeFile(workbook, `${name}.xlsx`)
}

// 模板下载
function downloadTemplate() {
  const tempalteInformation = [['机构网点号'],['4xxxxxxx']]
  const tempalteName = '机构网点渠道模板'
  exportToExcel(tempalteInformation, tempalteName)
}
/**
 * 导出渠道----------------
*/
async function exportCode() {
  // 获取活动渠道列表
  const channelList = await req.add(API_URL_ACTIVITY_CHANNEL_EXPORT, {
    channelCodes: exportList.value,
    channelType: 2,
  })
  exportChannelCode(channelList, 2)
}

/**
 * 展开
 */
async function show() {
  vdata.saveObject = {
    channelType: 2,
    isDistanceLimit: false,
  }
  resultList.value = []
  vdata.visible = true
  vdata.singleActiveKey = 1
}
// 关闭处理
function closeHandler() {
  vdata.visible = false
}
// 每次切换重置数据 
function changehdler(key) {
  vdata.singleActiveKey = key
  // 重置表单
  vdata.saveObject = {
    isDistanceLimit: false,
    fileList: [],
    agentNo: '',
    channelCode: '',
    agentNo4: '',
    distanceLimit: '',
     channelType: 2,
  }
  formRef.value.resetFields()
  resultList.value = []
}
defineExpose({
  show,
})
</script>
<style lang="less" scoped>
.choseText {
  color: #1890ff;
}

.container {
  width: 100%;
  padding-bottom: 30px;

  .step {
    width: 30%;
  }

  .textMerchant {
    width: 60%;
    margin-bottom: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .merchantResult {
    .information {
      display: flex;
      justify-content: right;
      margin-top: 30px;
    }
  }

  .form {
    margin: 30px;
    justify-content: center;
    overflow-y: auto;

    &::-webkit-scrollbar {
      display: none;
    }
  }
}

/deep/ .ant-upload-list-item-name {
  width: auto;
  flex-grow: 1 !important;
}
</style>